package com.dzl.cloud.produce;

import com.dzl.cloud.dto.LogMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

/**
 * @author 光的代言人
 */
@Service
@Slf4j
public class PermissionLogService {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void sendLog(LogMessageDTO message) {
        try {
            rocketMQTemplate.convertAndSend("operation-log-topic", message);
            log.info("发送权限操作日志：{}", message.getAction());
        } catch (MessagingException e) {
//            throw new RuntimeException(e);
//            log.error("发送权限操作日志失败：message:{}", e.getMessage(), e);
            // TODO: 此处应该添加重试或本地存储逻辑
            log.error("首次发送失败：{}", e.getMessage());
            handleRetry(message, e);
        }
    }

    private void handleRetry(LogMessageDTO message, Exception firstException) {
        // 最大重试次数
        final int maxRetries = 3;
        // 重试间隔1秒
        final long retryDelayMs = 1000;

        for (int attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                // 重试前等待
                Thread.sleep(retryDelayMs);

                // 尝试重发
                rocketMQTemplate.convertAndSend("operation-log-topic", message);
                log.info("重试成功（第{}次）：{}", attempt, message.getAction());
                return; // 重试成功则退出
            } catch (Exception retryEx) {
                log.warn("重试失败（第{}次）：{}", attempt, retryEx.getMessage());

                // 如果是最后一次尝试
                if (attempt == maxRetries) {
                    log.error("操作日志发送失败（{}次尝试后放弃）：{}",
                            maxRetries, message.getAction(), firstException);
                }
            }
        }
    }
}
